# 使用open方式读取文件,绝对路径
"""
f = open(r"D:\19th-issue-courseware\一阶段\day6\student.txt",encoding='utf-8')
result = f.read()
f.close() #最后别忘了关闭文件，系统资源的回收
print(result)
"""
# 通过相对路径读取
"""
f = open('student.txt',encoding='utf-8')
print(f.read())
f.close()
"""
# 通过with上下文管理，读取文件 'r'
"""
with open('student.txt','r',encoding='utf-8') as f:
    print(f.read()) # 读取文件方式，但是不需要close
"""
# 通过with，写入文件  ; “w”
"""
with open('student.txt','w',encoding='utf-8') as f: # as 是起个别名
    f.write("王长帅不是很帅") # 之前内容替换掉
"""
# 通过with，不存在的文件则新增:"w"
"""
with open('./class.txt','w',encoding='utf-8') as f:
    f.write("19期班级")
"""
# 通过with，追加写入："a"
"""
with open('student.txt','a',encoding='utf-8') as f:
    f.write("\n王长帅不是很帅")
    f.write("\n王长帅1")
    f.write("\n王长帅2")
"""
# 通过with，修改文件内容
# step：先拿到文件中的全部内容
with open('student.txt','r',encoding='utf-8') as f:
    all_data = f.read()
# step:替换内容，使用字符串的内置方法：replace
with open('student.txt','w',encoding='utf-8') as f:
    f.write(all_data.replace("王长帅不是很帅","王长帅不帅"))

# 使用with读取每一行的数据
with open('student.txt','r',encoding='utf-8') as f:
    print(f.readlines())












